# _*_ coding:utf-8 _*_
# @File  : middleware.py
# @Time  : 2021-03-17 13:39
# @Author: zizle

from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from hutool.security import decrypt_access_token
from configs import ADMIN_FLAG


# 新版本的FastAPI与APIRouter已经提供dependencies参数，可直接注入全局依赖列表，无需中间件来处理此类问题
# 这样就可方便为一组API去写一个属于它一组的依赖
class AdminAuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        # print('自定义中间件开始')
        # pprint.pprint(request.__dict__)
        # print('处理请求前的行为在这里执行...')
        if request.method != 'OPTIONS' and request.url.path.startswith('/admin'):
            if not self.admin_authenticated(request.headers.get('authorization', '')):
                return JSONResponse(status_code=403, content={'message': '登录过期或还没有该访问权限!', 'data': []})
        response = await call_next(request)
        # print('处理请求后的行为在这里执行...')
        # print('自定义中间件结束')
        # pprint.pprint(response.__dict__)
        return response

    @staticmethod
    def admin_authenticated(token):
        person = decrypt_access_token(token)
        if not person or ADMIN_FLAG not in person['access']:
            return False
        else:
            return True
